package db

import (
	"fmt"
	"strings"

	"git.sr.ht/~mil/mobroute/src/utilfuncs"
)

// LoadConnections loads the valid connections from the given input timespan
func (c *DBConnection) LoadConnections(
	dateYYYYMMDD uint,
	fromSeconds,
	toSeconds uint,
) (*[]Connection, error) {
	var (
		r     []Connection
		query = fmt.Sprintf(
			`
				select c.* from 
					_cvconnd c
					where from_stop_time between ? and ?
					and source || '_' || c.service_id in (
						select source || '_' || service_id
						from _vcaltoservice
							where service_date = ? and source in (%s)
					)
					order by from_stop_time asc
			`,
			strings.Join(utilfuncs.ArrayWithValue(len(c.QuerySources), "?"), ","),
		)
		params = append(
			[]any{
				any(fromSeconds), any(toSeconds), any(dateYYYYMMDD),
			},
			utilfuncs.Anyify(c.QuerySources)...,
		)
	)
	if err := queryToSlice(c, query, params, &r); err != nil {
		return nil, err
	} else {
		return &r, nil
	}
}
